package toDoList.Controllers;

import java.io.*;
import java.util.*;

import toDoList.Manager.DataBaseHelper;
import toDoList.Manager.R;
import toDoList.Manager.R.id;
import toDoList.Manager.R.layout;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class LoginController extends Activity implements ControllerInterface{

	//Instance Variables
	private SQLiteDatabase db;
	DataBaseHelper helper;
	
    /** Called when the activity is first created. */
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        try
        {
            helper = new DataBaseHelper(this);
        	helper.createDataBase();
        	db = helper.getWritableDatabase();
        	//db.execSQL("ALTER TABLE ToDoItem ADD COLUMN checked");
        }
        catch(IOException e)
        {
        	popUp(e.toString());
        }
    }
	
	private void deleteAllCategories()
	{
		db.execSQL("DELETE FROM Category");
	}

	public void deleteAllUsers()
	{
		db.execSQL("DELETE FROM User");
	}
	
	public void deleteAllItems()
	{
		db.execSQL("DELETE FROM ToDoItem");
	}
	
	/**
	 * createListener(): Used just to link classes together through the controllerInterface interface
	 */
	public void createListener()
	{
		 
	}
	
	
	/**
	 * validateUser(String name, String password) Validates the user on login, checking their name and password to the database
	 * @param name The name coming from the nameLoginText on the login UI
	 * @param password The password coming from the passwordLoginText on the login UI
	 * @return The name of the user being validated if it succeeds, otherwise null
	 */
	public String validateUser(String email, String password) {
		
		Cursor user = null;
		
		try
		{
			user = getUserByEmail(email);
		}
		catch(Exception e)
		{
			popUp("User isn't in the database.");
		}
		
		
		if(user != null)
		{
			try
			{
				if(user.getString(1).equals(email))
				{
					if(user.getString(2).equals(password))
					{
						return user.getString(0).toString();
					}
					else
					{
						return null;
					}
				}
				else
				{
					return null;
				}
			}
			catch(Exception e)
			{
				popUp("User isn't in the database.");
				return null;
			}
		}
		else
		{
			popUp("User isn't in the database.");
			return null;
		}
	}
	
	/**
	 * loginPressed(View view) Called when the login button in the login screen is pressed, logins if the username and password match and are
	 * in the database
	 * @param view This view
	 */
	public void loginPressed(View view)
	{
		String email = ((EditText)findViewById(R.id.emailLoginText)).getText().toString();
		String password = ((EditText)findViewById(R.id.passwordLoginText)).getText().toString();
		String name = "";
		
		if((name = validateUser(email, password)) != null)
		{
			Intent myIntent = new Intent(LoginController.this, ToDoListController.class);
			
			myIntent.putExtra("name", name);
			myIntent.putExtra("email", email);
			myIntent.putExtra("password", password);
			myIntent.putExtra("userGUID", getGUID(email));
			startActivity(myIntent);
		}
		else
		{
			popUp("Invalid Email or Password");
		}
	}
	
	private String getGUID(String email) {
		db = helper.getReadableDatabase();
		
	    Cursor mCursor =		
	      db.query(true, "User", new String[] {"email", "userGUID"}, "email" + " = " + "'" + email + "'", null,
	          null, null, null, null);
	    if (mCursor != null) {
	      mCursor.moveToFirst();
	    }
	    db.close();
	    return mCursor.getString(mCursor.getColumnIndex("userGUID"));
	}

	/**
	 * showUserView(View view) Runs when the user presses the "Create A New User" button
	 * @param view Usually null
	 */
	public void showUserView(View view)
	{
		Intent myIntent = new Intent(LoginController.this, UserController.class);
		startActivityForResult(myIntent, 1);
	}
	
	/**
	 * onActivityResult(int requestCode, int resultCode, Intent data) Based on the requestCode and resultCode, it will do an activiy after a sub-activity ends
	 * @param requestCode The requestCode passed back by the sub-activity
	 * @param resultCode The resultCode passed back by the sub-activity
	 * @param data The data passed back by the sub-activity
	 */
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		
		switch(requestCode)
		{
			case (1):
			{
				if(resultCode == RESULT_OK)
				{
						try 
						{
					 		SQLiteDatabase db = helper.getWritableDatabase();	
					 		db.execSQL("INSERT INTO User (name, email, password, userGUID) " + "VALUES (" + "'"+ data.getStringExtra("name") + "'" + ", " + "'"+ data.getStringExtra("email") + "'" + "," + "'" + data.getStringExtra("password") + "'" + ", '" + UUID.randomUUID().toString() +"')");
					 		db.close();
					 		
					 		Cursor c = getUserByName(data.getStringExtra("name"));
					 		popUp("New Account was created: " + c.getString(0).toString());
					 	}
						catch(SQLException sqle)
						{
					 		throw sqle;
					 	}
				}
			}
		}
	}
	
	/**
	 * getUser(String name) Gets the user with the name "name" from the database
	 * @param name The name to grab from the database
	 * @return A cursor with the data from the row with the name column valued "name"
	 * @throws SQLException
	 */
	public Cursor getUserByName(String name) throws SQLException {
		
	    db = helper.getReadableDatabase();
		
	    Cursor mCursor =		
	      db.query(true, "User", new String[] {"name",
	          "email", "password"}, "name" + " = " + "'" + name + "'", null,
	          null, null, null, null);
	    if (mCursor != null) {
	      mCursor.moveToFirst();
	    }
	    db.close();
	    return mCursor;
	 
	  }
	
	/**
	 * getUser(String name) Gets the user with the email "email" from the database
	 * @param email The email to grab from the database
	 * @return A cursor with the data from the row with the name column valued "email"
	 * @throws SQLException
	 */
	public Cursor getUserByEmail(String email) throws SQLException {
		
	    db = helper.getReadableDatabase();
		
	    Cursor mCursor =		
	      db.query(true, "User", new String[] {"name",
	          "email", "password"}, "email" + " = " + "'" + email + "'", null,
	          null, null, null, null);
	    if (mCursor != null) {
	      mCursor.moveToFirst();
	    }
	    db.close();
	    return mCursor;
	 
	  }
	
	
	/**
	 * showToDoListView() Starts a new ToDoList Activity and passes the validates User
	 */
	public void showToDoListView() {
		throw new UnsupportedOperationException("The method is not implemented yet.");
	}

	/**
	 * updateView() Updates the user.xml view
	 */
	public void updateView() {
		throw new UnsupportedOperationException("The method is not implemented yet.");
	}
	
	/**
	 * popUp(String n) Displays a pop-up window with the message "n" inside of it.
	 * @param n The string to display
	 */
	public void popUp(String n)
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(n)
		       .setCancelable(false)
		       .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
		
		builder.show();
	}
}
